#include "SQLcommand_impl.h"

namespace utility
{
namespace database
{
    SQLcommand_impl::SQLcommand_impl(const char * SQLText, database_connection * conn)
    {
        _connection = conn;
        _type = NOT_DEFINED;
        _SQL_text = SQLText;
        //_async_handler = NULL;
    }

    SQLcommand_impl::~SQLcommand_impl(void)
    {
        //delete _async_handler;
    }

    const char * SQLcommand_impl::get_text()
    {
        return _SQL_text.c_str();
    }

    const char * SQLcommand_impl::get_SQL()
    {
        _SQL = "";
        SQLparameters::const_iterator iCur = parameters.begin();
        for (; iCur != parameters.end(); iCur++)
        {
            SQLparameters::const_reference value = *iCur;
            if (value.second->direction == InputOutput)
            {
                _SQL += "set ";
                _SQL += value.first;
                _SQL += '=';
                _SQL += value.second->to_string(_connection);
                _SQL += ';';
            }
        }

        std::string name;
        const char * s = _SQL_text.c_str();
        while (*s)
        {
            if (*s == '@')
            {
                name = "";
                while (*s && *s != ' ' && *s != ',' && *s != ')')
                {
                    name += *s++;
                }
                parameter_base * param = parameters.get(name.c_str());
                if (param && (param->direction == Input))
                {
                    _SQL += param->to_string(_connection);
                }
                else
                {
                    _SQL += name;
                }
            }
            else
                _SQL += *s++;
        }
        return _SQL.c_str();
    }

    const char * SQLcommand_impl::get_procedure_output_value()
    {
        SQLparameters::const_iterator iCur = parameters.begin();
        SQLparameters::const_iterator iEnd = parameters.end();
        _SQL = "SELECT ";
        int count = 0;
        for (; iCur != iEnd; iCur++)
        {
            SQLparameters::const_reference value = *iCur;
            if (value.second->direction != Input)
            {
                if (count == 0)
                    _SQL += value.first;
                else
                    _SQL += (',' + value.first);
                ++count;
            }
        }
        if (count == 0)
            _SQL = "";
        return _SQL.c_str();
    }


}
}

